package com.huasan.www.demon.rest.resource;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.server.mvc.Viewable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.huasan.www.demon.data.service.FeedbackService;
import com.huasan.www.demon.pojo.FeedbackExample;
import com.huasan.www.demon.pojo.FeedbackWithBLOBs;
import com.huasan.www.demon.rest.util.Constants;
import com.huasan.www.demon.util.DataTableUtil;
import com.huasan.www.demon.util.OnePage;

@Path("/helper")
public class FeedbackResource extends Resource{

	@Autowired
	private FeedbackService feedbackService;
	
	private Logger logger = LoggerFactory.getLogger(FeedbackResource.class);
	
	private static final String basePath = new File(System.getProperty("demon.webapp.root")) + File.separator 
											+ ".." + File.separator + ".." 
												+ File.separator + "files" + File.separator;
	
	@GET
	@Path("/editPage")
	@Produces("text/html")
	public Response editPage() {
		httpServletRequest.getSession().removeAttribute("demonsid");
		return Response.ok(new Viewable("/WEB-INF/demon/editPage"))
				.cookie(new NewCookie("demonsid", null, "/",null, null, Constants.DURATION_CLEAR, false))
				.build();
	}
	
	@GET
	@Produces({MediaType.TEXT_HTML} )
	public Response helper(){
		return Response.ok().entity("Helper").build();
	}
	
	@GET
	@Path("page")
	@Produces({MediaType.TEXT_HTML} )
	public Response page(@QueryParam("page") String page){
		try{
			logger.info("Page base path =>" + basePath);
			File file = new File(basePath+"pages"+File.separator+page);
			if (!file.exists() || file.isDirectory())
				return Response.status(404).entity("Can not find the page").build();
			
			String str = "";
			StringBuilder ret = new StringBuilder();
			BufferedReader in = new BufferedReader(new FileReader(file));
			while ((str = in.readLine()) != null) 
            {
				ret.append(str);
            }
			in.close();
			return Response.ok().entity(ret.toString()).build();
		}catch(Exception e){
			logger.error(e.getMessage(),e);
			return Response.status(404).entity("Can not find the page").build();
		}
	}
	
	@GET
	@Path("intr")
	@Produces({MediaType.TEXT_HTML} )
	public Response introdustion(){
		try {
			return Response.temporaryRedirect(new URI("helper/page?page=intr")).build();
		} catch (URISyntaxException e) {
			return Response.status(404).entity("Can not find page").build();
		}
	}
	
	@GET
	@Path("about")
	@Produces({MediaType.TEXT_HTML} )
	public Response about(){
		try {
			return Response.temporaryRedirect(new URI("helper/page?page=about")).build();
		} catch (URISyntaxException e) {
			return Response.status(404).entity("Can not find page").build();
		}
	}
	
	@GET
	@Path("guide")
	@Produces({MediaType.TEXT_HTML} )
	public Response guide(){
		try {
			return Response.temporaryRedirect(new URI("helper/page?page=guide")).build();
		} catch (URISyntaxException e) {
			return Response.status(404).entity("Can not find page").build();
		}
	}
	
	@POST
	@Path("comment")
	@Produces({MediaType.APPLICATION_JSON} )
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public String insertComment(@FormParam("userid") String userid, @FormParam("comment") String comment,
			@FormParam("priority") String priority, @FormParam("pid") String pid){
		try{
			if (comment==null || "".equals(comment))
				return getErrReturn("请输入评论内容");
			Long uid = Long.valueOf(userid);
			Long pId = pid==null||"".equals(pid)?null:Long.valueOf(pid);
			FeedbackWithBLOBs feedback = new FeedbackWithBLOBs();
			feedback.setUserid(uid);
			feedback.setPid(pId);
			feedback.setPriority(priority);
			feedback.setComment(comment);
			feedbackService.insertSelective(feedback);
			return getSucReturn("评论成功");
		}catch(Exception e){
			logger.error(e.getMessage(),e);
			return getErrReturn("评论失败，请重试");
		}
	}
	
	@GET
	@Path("comment_p")
	@Produces({MediaType.APPLICATION_JSON} )
	public String getCommentsByUid(@QueryParam("userid") String userid, @QueryParam("pid") String pid,
			@QueryParam("priority") String priority, @QueryParam("sEcho") String sEcho,
			@QueryParam("iDisplayStart") Integer iDisplayStart,
			@QueryParam("iDisplayLength") Integer iDisplayLength){
		try{
			FeedbackExample example = new FeedbackExample();
			FeedbackExample.Criteria criteria = example.createCriteria();
			if (userid!=null && !"".equals(userid))
				criteria.andUseridEqualTo(Long.valueOf(userid));
			if (pid!=null && !"".equals(pid))
				criteria.andPidEqualTo(Long.valueOf(pid));
			if (priority!=null && !"".equals(priority))
				criteria.andPriorityLike("%"+priority+"%");
			
			Integer total = feedbackService.countByExample(example);
			
			example.setLimitStart(iDisplayStart);
			example.setLimitEnd(iDisplayLength);
			OnePage<FeedbackWithBLOBs> page = feedbackService.selectOneBlobPageByExample(example);
			
			return DataTableUtil.getDataTable(sEcho, total, total
					, objectmapper.writeValueAsString(page.getDataList()));
		}catch(Exception e){
			logger.error(e.getMessage(),e);
			return getErrReturn("获取评论失败，请重试");
		}
	}
	
	@GET
	@Path("comment_a")
	@Produces({MediaType.APPLICATION_JSON} )
	public String getCommentsByUid(@QueryParam("userid") String userid, @QueryParam("pid") String pid,
			@QueryParam("priority") String priority){
		try{
			FeedbackExample example = new FeedbackExample();
			FeedbackExample.Criteria criteria = example.createCriteria();
			if (userid!=null && !"".equals(userid))
				criteria.andUseridEqualTo(Long.valueOf(userid));
			if (pid!=null && !"".equals(pid))
				criteria.andPidEqualTo(Long.valueOf(pid));
			if (priority!=null && !"".equals(priority))
				criteria.andPriorityLike("%"+priority+"%");
			List<FeedbackWithBLOBs> feedbacks = feedbackService.selectByExampleWithBLOBs(example);
			return this.getSucReturn(objectmapper.writeValueAsString(feedbacks),"");
		}catch(Exception e){
			logger.error(e.getMessage(),e);
			return getErrReturn("获取评论失败，请重试");
		}
	}
	
	@GET
	@Path("pageContent")
	@Produces({MediaType.APPLICATION_JSON} )
	public String getPageContent(@QueryParam("page") String page){
		try{
			logger.info("Page base path =>" + basePath);
			File file = new File(basePath+"pages"+File.separator+page);
			if (!file.exists() || file.isDirectory())
				return "";
			
			String str = "";
			StringBuilder ret = new StringBuilder();
			BufferedReader in = new BufferedReader(new FileReader(file));
			while ((str = in.readLine()) != null) 
            {
				ret.append(str);
            }
			in.close();
			return ret.toString();
		}catch(Exception e){
			logger.error(e.getMessage(),e);
			return "";
		}finally {
			
		}
	}
	
	@POST
	@Path("savePage")
	@Produces({MediaType.APPLICATION_JSON} )
	public String savePageContent(@FormParam("page") String page, @FormParam("content") String content){
		try{
			if (page==null)
				return this.getErrReturn("page为空");
			logger.info("Page base path =>" + basePath);
			File directory = new File(basePath + "pages");
			if (!directory.exists())
				directory.mkdirs();
			File file = new File(basePath+"pages"+File.separator+page);
			if (!file.exists())
				file.createNewFile();
			FileWriter writer = new FileWriter(file, false);
			BufferedWriter bw = new BufferedWriter(writer);
			bw.write(content);
			bw.close();
			writer.close();
			return this.getSucReturn("");
		}catch(Exception e){
			logger.error(e.getMessage(),e);
			return getErrReturn("写入页面信息失败，请重试");
		}
	}
}
